const fs = require("fs-extra");
const path = require("path");

// 导入各种格式的生成器
const jsonGenerator = require("./json");
const stringsGenerator = require("./strings");
const xmlGenerator = require("./xml");
const jsGenerator = require("./js");
const arbGenerator = require("./arb");

const generators = {
  json: jsonGenerator,
  strings: stringsGenerator,
  xml: xmlGenerator,
  js: jsGenerator,
  arb: arbGenerator,
  stringsdict: stringsGenerator, // iOS stringsdict 使用 strings 生成器的扩展
};

class FileGenerator {
  static async generate(format, data, filePath, platform = "web") {
    const generator = generators[format];

    if (!generator) {
      throw new Error(`不支持的文件格式: ${format}`);
    }

    // 生成文件内容
    const content = await generator.generate(data, platform);

    // 确保目录存在
    await fs.ensureDir(path.dirname(filePath));

    // 写入文件
    await fs.writeFile(filePath, content, "utf8");

    return filePath;
  }

  static async generateContent(format, data, platform = "web") {
    const generator = generators[format];

    if (!generator) {
      throw new Error(`不支持的文件格式: ${format}`);
    }

    return await generator.generate(data, platform);
  }

  static getSupportedFormats(platform = "web") {
    const platformFormats = {
      web: ["json"],
      ios: ["strings", "stringsdict"],
      android: ["xml"],
      rn: ["json"],
      flutter: ["arb", "json"],
    };

    return platformFormats[platform] || platformFormats.web;
  }

  static validateFormat(format, platform = "web") {
    const supportedFormats = this.getSupportedFormats(platform);
    return supportedFormats.includes(format);
  }
}

module.exports = {
  generate: FileGenerator.generate.bind(FileGenerator),
  generateContent: FileGenerator.generateContent.bind(FileGenerator),
  getSupportedFormats: FileGenerator.getSupportedFormats.bind(FileGenerator),
  validateFormat: FileGenerator.validateFormat.bind(FileGenerator),
};
